package org.ui.maven.plugin.maven_ui_deploy_plugin;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 */
@Mojo(name = "zip")
public class ZipMojoSupport extends AbstractMojo {

	@Parameter
	protected String[] includes;

	@Parameter
	protected String[] excludes;

	@Parameter(defaultValue = "${basedir}/src/main/webapp")
	private File sourceDirectory;
	@Parameter(defaultValue = "${basedir}/src/main/webapp")
	private String webapp;
	
	@Parameter(defaultValue="${project.build.directory}/${project.build.finalName}")
	private String dest;


	
	List<File> jspFiles = new ArrayList<File>(50);
	List<File> deleteFiles = new ArrayList<File>(50);
	HashMap<String, String> jsmapping = new HashMap<String, String>();
	public void execute() throws MojoExecutionException, MojoFailureException {
		HashMap<String, String> csssmapping = jsmapping ;// new HashMap<String, String>();
		handler(sourceDirectory,jsmapping, csssmapping);
		getLog().info(jsmapping.toString());
		getLog().info(csssmapping.toString());
		repJsp();
	}

	private void repJsp() {
		dest = dest.replace("\\", File.separator).replace("/", File.separator);
		String replace = webapp.replace("/", File.separator);
		for(File jsp : this.jspFiles){
			if(jsp.exists()){
				String readJsp2String = this.readJsp2String(jsp);
				for(Map.Entry<String, String> entry :this.jsmapping.entrySet()){
					readJsp2String = readJsp2String.replace(entry.getKey(), entry.getValue());
				}
				String savePath = jsp.getPath().replace(replace, dest);
				write2File(savePath,readJsp2String);
			};
		}
		File file2 = new File(dest+".war");
		if(file2.isFile()){
			file2.delete();
		}
		for(File file : deleteFiles){
			String replace2 = file.getPath().replace(replace, dest);
			File file3 = new File(replace2);
			if(file3.isFile()){
				file3.delete();
			}
		}
		
		ZipUtils.createZip(dest, dest+".war");
		getLog().info("重新生成war成功" + dest+".war");
		
	}

	private void write2File(String savePath, String readJsp2String) {
		try {
			File file = new File(savePath);
			if(file.exists()){
				file.delete();
			}
			file.createNewFile();
			try(BufferedWriter bf = new BufferedWriter(new FileWriter(file))){
				bf.write(readJsp2String);
				bf.flush();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private String readJsp2String(File jsp) {
		StringBuilder dest = new StringBuilder();
		try(BufferedReader reader = new BufferedReader(new FileReader(jsp))){
			String line = null;
			while((line = reader.readLine())!= null){
				dest.append(line);
			}
			return dest.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private void handler(File file,Map<String,String> jsmapping, Map<String,String> csssmapping) {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				File srcFile = files[i];
				if(srcFile.isFile()){
					handleFile(jsmapping, csssmapping, srcFile);
				}else if(srcFile.isDirectory()){
					this.handler(srcFile,jsmapping, csssmapping);
				}
			}
		} else if (file.isFile()) {
			if (!file.getName().startsWith(".")) {
			this.handleFile(jsmapping, csssmapping, file);
			}

		}
	}

	private void handleFile(Map<String, String> jsmapping,
			Map<String, String> csssmapping, File srcFile) {
		if(srcFile.getName().endsWith(".jsp")){
			this.jspFiles.add(srcFile);
			return;
		}
		String name = "${ctx}"+getPath(srcFile);
		if (srcFile.getName().endsWith(".js")){
			jsmapping.put(name, this.getCDNUrl(srcFile.getName(),JSCSSZipHelpr.compress2JS(srcFile)));
			this.deleteFiles.add(srcFile);
		}
		else if (srcFile.getName().endsWith(".css")){
			csssmapping.put(name, this.getCDNUrl(srcFile.getName(),JSCSSZipHelpr.compress2CSS(srcFile)));
			this.deleteFiles.add(srcFile);			
		}
	}

	private String getPath(File srcFile) {
		return srcFile.getPath().replace(webapp.replace("/", File.separator), "").replace(File.separator, "/");
	}
	
	private String getCDNUrl(String name, String dest) {
		return "http://www.cdn.com/"+name;
	}

}